var musicAudio = document.querySelector('#mic_audio'); // audio标签
var channel = document.querySelector('.channel'); // 频道标签节点
var songTitle = document.querySelector('.song-title'); // 歌名标签节点
var singer = document.querySelector('.singer'); // 歌手标签节点
var recordImg = document.querySelector('.record-pic img'); // 专辑图片
var recordPic = document.querySelector('.record-pic'); // 专辑图片外层div节点
var recordWrap = document.querySelector('.record-wrapper'); // 专辑区域
var playBtn = document.querySelector('.play'); // 播放按钮
var nextBtn = document.querySelector('.next'); // 下一区按钮
var changeChannelBtn = document.querySelector('.change-channel'); // 更换频道
var modeBtn = document.querySelector('.mode'); // 切换播放模式
var progressBar = document.querySelector('.progress-bar'); // 进度条外层div
var progress = document.querySelector('.progress');  // 进度条长度
var progressBtn = document.querySelector('.progress-btn'); // 进度条拖动按钮
var lyricBtn = document.querySelector('.show-lyrics'); // 显示歌词按钮
var lyrics = document.querySelector('.lyrics'); // 歌词的包裹节点
var bigBg = document.querySelector('.glass img');
var lyricsLiArr = null;

getMusic();

// 为播放按钮添加事件
playBtn.onclick = function () {
    musicAudio.onplaying = null;  //  清除audio标签绑定的事件
    if (musicAudio.paused) {
        playBtn.style.backgroundImage = 'url(images/play.png)';
        musicAudio.play();
    } else {
        playBtn.style.backgroundImage = 'url(images/stop.png)';
        musicAudio.pause();
    }
};
// 下一曲按钮
nextBtn.onclick = function () {
    playMusic(null, 'next');
};

// 上一首
changeChannelBtn.onclick = function () {
    playMusic(null, 'prev');
};

// 显示信息dialog
modeBtn.onclick = function () {
    $('.dialog.dialog-info').removeClass('hide');
};
$('button.close-btn').click(function () {
    $('.dialog.dialog-info').addClass('hide');
})
// 显示歌单
lyricBtn.onclick = function () {
    $('.music-menu-content').toggleClass('in')
    $('.music-menu-content li.active').removeClass('active')
    $('.music-menu-content li:eq(' + gdata.currentIndex + ')').addClass('active');
    return false;
};
$('.music-menu-content')[0].onclick = function (e) {
    if ($(e.target).hasClass('music-menu-content')) {
        $('.music-menu-content').toggleClass('in')
    }
    return false;
}


var isLoading = false;
var progressTimer = setInterval(activeProgressBar, 300);

// 激活进度条
function activeProgressBar() {
    var percentNum = Math.floor((musicAudio.currentTime / musicAudio.duration) * 10000) / 100 + '%';
    progress.style.width = percentNum;
    progressBtn.style.left = percentNum;

    if (percentNum == '100%' && !isLoading && !musicAudio.loop) {
        isLoading = true;
        playMusic(null, 'next');
    }
    if (musicAudio.paused && recordPic.className != 'record-pic mid') {
        recordPic.className = 'record-pic mid';
        playBtn.style.backgroundImage = 'url(images/stop.png)';
        return;
    } else if (recordPic.className != 'record-pic mid rotate' && !musicAudio.paused) {
        recordPic.className = 'record-pic mid rotate';
        playBtn.style.backgroundImage = 'url(images/play.png)';
    }

    // 控制歌词动态滚动
    if (lyricsLiArr) {
        for (var i = 0, len = lyricsLiArr.length - 1; i < len; i++) {
            var curT = lyricsLiArr[i].getAttribute('data-time');
            var nexT = lyricsLiArr[i + 1].getAttribute('data-time');
            var curtTime = musicAudio.currentTime;
            if ((curtTime > curT) && (curtTime < nexT)) {
                lyricsLiArr[i].className = 'active';
                lyrics.style.top = (100 - lyricsLiArr[i].offsetTop) + 'px';
            } else {
                lyricsLiArr[i].className = '';
            }
        }
    }
}

// 进度条操作音乐播放进度，绑定事件
progressBtn.addEventListener('touchstart', function () {
    clearInterval(progressTimer);
});
progressBtn.addEventListener('touchmove', function (e) {
    var percentNum = (e.targetTouches[0].pageX - progressBar.offsetLeft) / progressBar.offsetWidth;
    if (percentNum > 1) {
        percentNum = 1;
    } else if (percentNum < 0) {
        percentNum = 0;
    }
    this.style.left = percentNum * 100 + '%';
    progress.style.width = percentNum * 100 + '%';
});
progressBtn.addEventListener('touchend', function (e) {
    var percentNum = (e.changedTouches[0].pageX - progressBar.offsetLeft) / progressBar.offsetWidth;
    musicAudio.currentTime = musicAudio.duration * percentNum;
    progressTimer = setInterval(activeProgressBar, 300);
});

function playMusic(index, type) {
    if (!index && type) {
        if (type == 'next') {
            //下一曲
            index = gdata.currentIndex + 1;
            if (gdata.musicList.length <= index) {
                index = 0;
            }
        } else if (type == 'prev') {
            index = gdata.currentIndex - 1
            if (index < 0) {
                index = gdata.musicList.length - 1
            }
        }
    }
    let songObj = gdata.musicList[index]
    songTitle.innerHTML = songObj.name + ' - ' + songObj.author;
    singer.innerHTML = songObj.author;
    document.title = songObj.name
    recordImg.src = `http://files100.oss-cn-beijing.aliyuncs.com/taijiao/img/${songObj.no}.jpg`;
    bigBg.src = `http://files100.oss-cn-beijing.aliyuncs.com/taijiao/img/${songObj.no}.jpg`;
    musicAudio.src = `http://files100.oss-cn-beijing.aliyuncs.com/taijiao/${songObj.no}.mp3`
    musicAudio.load()
    musicAudio.play();
    isLoading = false;
    gdata.currentIndex = index;
    //这是每首歌开始时的播放明细。点一下首，或者，自动播放时提交一下
    ajax({
        url: '/api/taijiao/submitplaydetail',
        type: 'POST',
        data: {
            musicNo: songObj.no,
            playStartTime: new Date().format('yyyyMMddhhmmss'),
            timeStr: gdata.timeStr,
            openid: gdata.openid
        }
    })

    gdata.wxShareConfig = {
        title: document.title, // 分享标题
        link: location.href, // 分享链接
        imgUrl: gdata.musicList[gdata.currentIndex || 0] ? `http://files100.oss-cn-beijing.aliyuncs.com/taijiao/img/${gdata.musicList[gdata.currentIndex || 0].no}.jpg` : location.origin + '/images/pic.jpg',
        success: function (res) {
            alert('已分享');
        },
        cancel: function (res) {
            alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    }
}

// 获取音乐
function getMusic() {
    ajax({
        url: '/api/taijiao/getmusic/' + gdata.month + '?openid=' + gdata.openid,
        type: 'GET',
        success: function (res) {
            gdata.musicList = res
            let playIndex = 0;
            gdata.musicList.map((item, index) => {
                if (item.no == gdata.last_music_no) {
                    playIndex = index;
                }
            })
            playMusic(playIndex)
            //渲染music menu
            $('.musiclist .container').html('')
            gdata.musicList.map((item, index) => {
                let $li = $(`<li data-index="${index}" class="">
                                    <div class="border-1px"></div> 
                                    <i class="playingicon icon-volume-medium" style="display: none;"></i>
                                    <span>${item.month}月胎教 -</span>
                                    <span class="name">${item.name}</span> <span class="singer"> - ${item.author}</span> <i class="close"></i> <div class="border-1px"></div>
                                </li>`);
                $('.musiclist .container').append($li)
            })
        }
    })
    return false;

};

function PrefixInteger(num, n) {
    return (Array(n).join(0) + num).slice(-n)
}
function formatDuring(mss) {
    var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60))
    var seconds = (mss % (1000 * 60)) / 1000
    return (PrefixInteger(parseInt(minutes), 2) + ':' + PrefixInteger(parseInt(seconds), 2))
}
setInterval(() => {
    let ms = new Date().getTime() - gdata.timeStr
    if (parseInt(ms / 1000) % 5 === 0) {
        ajax({
            url: '/api/taijiao/submitplaytime',
            type: 'POST',
            data: {
                playStartTime: new Date(gdata.timeStr).format('yyyyMMddhhmmss'),
                playTotalTime: parseInt(ms / 1000),
                timeStr: gdata.timeStr,
                openid: gdata.openid
            }
        })
    }
    let useTime = formatDuring(ms)
    $('#usetime').text(useTime)

}, 1000)
$(document).on('click', '.musiclist li', function () {
    let index = $(this).index();
    playMusic(index);
    $('.music-menu-content').toggleClass('in')
    $(this).addClass('active').siblings('.active').removeClass('active')
})
document.addEventListener("WeixinJSBridgeReady", function () {
    var audio = document.getElementById('mic_audio');
    audio.play();
}, false);

//-------------------------------------------
$('.dialog.dialog-info .date').text(new Date().format('yyyy-MM-dd'));
$('.dialog.dialog-info .pregnancy_days').text(gdata.pregnancy_days);
$('.dialog.dialog-info .pregnancy_weektps').text(gdata.pregnancy_weektps);
$('.dialog.dialog-info .pregnancy_childbirth_date').text(gdata.pregnancy_childbirth_date);
$('.dialog.dialog-info .pregnancy_remain_days').text(gdata.pregnancy_remain_days);


// ----------------------------------
wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: gdata.appid, // 必填，公众号的唯一标识
    timestamp: gdata.timestamp, // 必填，生成签名的时间戳
    nonceStr: gdata.nonceStr, // 必填，生成签名的随机串
    signature: gdata.signature,// 必填，签名，见附录1
    jsApiList: ["checkJsApi", "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareQZone"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
});

try {
    wx.ready(function () {
        document.querySelector('#checkJsApi').onclick = function () {
            wx.checkJsApi({
                jsApiList: [
                    'getNetworkType',
                    'previewImage'
                ],
                success: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };
        //朋友圈
        wx.onMenuShareTimeline(gdata.wxShareConfig);
        //朋友
        wx.onMenuShareAppMessage($.extend(gdata.wxShareConfig, {
            type: '', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        }));
    });
} catch (err) {
    console.log(err)
}